# src/web/app.py
from flask import Flask, request, jsonify
from flask_cors import CORS  # ⬅️ 新增这一行
from models.database import DatabaseManager
from models.comment_schema import VideoSource
from utils.config_loader import Config
import re
import logging

# 初始化 Flask 应用
app = Flask(__name__, static_folder='static', template_folder='templates')
CORS(app, resources={r"/*": {"origins": "*"}}) 

# 设置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 获取数据库配置
config = Config()
db_manager = DatabaseManager(config.DB_CONFIG)


def extract_video_id(url):
    """
    提取 YouTube、Facebook 或 Discord 的 video_id
    支持格式：
        - YouTube: https://youtu.be/abc123 | https://www.youtube.com/watch?v=abc123
        - Facebook: https://www.facebook.com/watch/?v=734974418925764
        - Discord: https://discord.com/channels/123456/789012
    """
    if 'youtube' in url or 'youtu.be' in url:
        match = re.search(r'(?:v=|\/)([0-9A-Za-z_-]{11})(?:\?|&|$)', url)
        return match.group(1) if match else None
    elif 'facebook.com' in url:
        # 支持多种 Facebook 链接格式
        match = re.search(r'(?:v=|videos\/|watch\/\?v=)(\d+)', url)
        return match.group(1) if match else None
    elif 'discord' in url:
        match = re.search(r'channels\/(\d+/\d+)', url)
        return match.group(1) if match else None
    else:
        logger.warning(f"⚠️ 不支持的平台: {url}")
        return None


@app.route('/api/video', methods=['POST'])
def add_video():
    data = request.get_json()

    logger.info(f"📥 收到请求数据: {data}")

    video_url = data.get('video_url')
    title = data.get('title')
    car_brand = data.get('car_brand')  # 品牌字段来自前端输入

    if not video_url or not title:
        logger.warning("⚠️ 缺少必要参数")
        return jsonify({"error": "缺少必要参数"}), 400

    video_id = extract_video_id(video_url)
    if not video_id:
        logger.warning(f"⚠️ 无法从链接中提取视频ID: {video_url}")
        return jsonify({"error": "无法从链接中提取视频ID"}), 400

    platform = 'youtube' if 'youtube' in video_url else \
               'facebook' if 'facebook' in video_url else \
               'discord' if 'discord' in video_url else 'unknown'

    session = db_manager.Session()
    try:
        logger.info(f"🔌 当前数据库连接: {db_manager.engine.url}")

        # 检查是否已存在相同的视频源
        existing_source = session.query(VideoSource).filter_by(video_url=video_url).first()
        if existing_source:
            logger.info(f"🔄 视频源已存在: {video_id}")
            return jsonify({"message": f"🔄 视频源已存在: {video_id}"}), 200

        video_source = VideoSource(
            video_url=video_url,         # ✅ 新增这一行：保存原始 URL
            video_id=video_id,
            title=title,
            author=data.get('author'),
            views=data.get('views'),
            comment_count=data.get('comment_count'),
            publish_date=data.get('publish_date'),
            platform=platform,
            brand=car_brand              # 使用 brand 替代 extra_attributes
        )
        session.add(video_source)
        session.commit()
        logger.info(f"✅ 成功添加视频源：{video_id}")
        return jsonify({"message": f"✅ 成功添加视频源：{video_id}"})
    except Exception as e:
        session.rollback()
        logger.error(f"❌ 添加视频源失败: {str(e)}", exc_info=True)
        return jsonify({"error": str(e)}), 500
    finally:
        session.close()


# 新增路由：提供前端页面
# src/web/app.py 修改部分
@app.route('/')
def index():
    try:
        with open('src/views/video_table.html', encoding='utf-8') as f:
            content = f.read()
            logger.info(f"📄 页面长度: {len(content)} 字节")
            return content
    except Exception as e:
        logger.error(f"❌ 加载页面失败: {str(e)}")
        return "500 Internal Server Error", 500

@app.route('/list_videos')
def list_videos():
    with open('src/views/list_video_sources.html', encoding='utf-8') as f:
        return f.read()


@app.route('/api/videos', methods=['GET'])
def get_all_videos():
    session = db_manager.Session()
    try:
        logger.info("🔍 开始查询所有视频源数据")
        results = session.query(VideoSource).all()
        logger.info(f"✅ 成功获取 {len(results)} 条视频源数据")

        video_list = []
        for v in results:
            # 尝试从 brand 字段获取品牌信息，如果为空则尝试从 extra_attributes 获取
            brand = None
            if hasattr(v, 'brand') and v.brand:
                brand = v.brand
            elif hasattr(v, 'extra_attributes') and v.extra_attributes:
                brand = v.extra_attributes.get('car_brand', '-')
            
            video_data = {
                "id": v.id,
                "video_title": v.title,
                "publish_date": v.publish_date.strftime("%Y-%m-%d") if v.publish_date else None,
                "platform": v.platform,
                "brand": brand or '-',  # 确保品牌字段不为空
                "comment_count": v.comment_count or 0,
                "view_count": v.views or 0,
                # 新增字段：字幕处理状态
                "subtitle_processed": getattr(v, 'subtitle_processed', None),
                "subtitle_process_status": "已完成" if getattr(v, 'subtitle_processed', 0) == 1 else "未完成",
                "comment_process_status": getattr(v, 'comment_process_status', None) or "未处理"
            }
            video_list.append(video_data)
            
        return jsonify(video_list)
    except Exception as e:
        logger.error(f"❌ 获取视频源失败: {str(e)}", exc_info=True)
        return jsonify({"error": str(e)}), 500
    finally:
        session.close()

@app.route('/video_table')
def video_table():
    with open('src/views/video_table.html', encoding='utf-8') as f:
        return f.read()
    
@app.route('/video_add')
def video_add():
    with open('src/views/video_add.html', encoding='utf-8') as f:
        return f.read()

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)